<!-- KPI组件 -->
<template>
  <div class="wrap">
    <div class="wrap-header">
      <span class="wrap-header-title">工作业绩考核（KPI）</span>
      <span>维度权重：{{ props.weight }}% </span>
    </div>

    <div style="margin-bottom: 20px">
      <div class="header">
        <div style="margin-left: 10px">维度考核工具：关键业绩考核（KPI）</div>
        <div>
          <a-button type="text">引用指标库</a-button>
          <a-button type="text">工具设置</a-button>
          <a-button type="text" @click="setExtra = !setExtra"
            >开启加减分</a-button
          >
        </div>
      </div>
      <div>
        <a-table
          :columns="columns"
          ref="tableRef"
          :data="KpiData.data"
          :bordered="{ headerCell: true }"
          stripe
        >
          <template #optional="{ record, rowIndex }">
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="add(record, rowIndex)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record, rowIndex)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table>
        <a-button type="text" @click="add(null)">新增指标</a-button>
      </div>
    </div>

    <div v-show="setExtra">
      <div class="wrap-header">
        <div class="wrap-header-title">加减分项</div>
      </div>
      <div>
        <a-table
          :columns="extraColumns"
          ref="tableRef"
          :data="KpiData.extraData"
          :bordered="{ headerCell: true }"
          stripe
        >
          <template #optional="{ record, rowIndex }">
            <a-tooltip content="编辑">
              <icon-font
                type="icon-edit"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="addExtra(record, rowIndex)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="delExtra(record, rowIndex)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table>
        <a-button type="text" @click="addExtra(null)">新增指标</a-button>
      </div>
    </div>
  </div>
  <IndexDrawer
    v-model:visible="visible"
    @kpiIndexEmit="kpiIndexEmit"
    :data="currData"
    :weight="props.weight"
    :maxWeight="maxWeight"
  ></IndexDrawer>
  <div>
    <ExtraDrawer
      v-model:visible="extraVisible"
      @kpiExtraIndexEmit="kpiExtraIndexEmit"
      :data="currExtraData"
    ></ExtraDrawer>
  </div>
</template>

<script lang="ts" setup>
import { DelProbationTemplateTool } from '@/apis/management/performance/baseSetting/template';
import IndexDrawer from './IndexDrawer.vue';
import ExtraDrawer from './ExtraDrawer.vue';

const props = withDefaults(
  defineProps<{
    weight?: any; // 维度权重,
  }>(),
  {}
);

const emits = defineEmits(['update:visible', 'kpiIndexEmit']);

const KpiData = reactive({
  /*
    source: undefined, // 指标来源
    type: undefined, // 指标类型
    name: '', // 指标名称
    definition: '', // 指标定义
    define: '', // 项目界定
    nature: undefined, // 指标极性
    formula: '', // 指标公式/说明
    rule: '', // 评分标准/规则
    upper: undefined, // 评分上限
    weight: undefined, // 指标权重
    target: [
      {
        reference: undefined, // 基准值
        goal: undefined, // 目标值
        challenge: undefined // 挑战值
      }
    ],
    dataSource: undefined, // 数据来源，评分人
    dimensionaId: undefined, // 纬度id
    units: '', // 考核目标单位
    writeWay: 1, // 实际值录入1关 2由考核发起时指定 3直接指定录入人员
    markWay: 1, // 评分方式 1 直接输入 2 公式计算
    remark: '', // 备注
    isAddStore: false // 是否新增到指标库
  */
  data: [],
  /*
    name: '', // 指标名称
    definition: '', // 指标定义
    define: '', // 项目界定
    rule: '', // 评分标准/规则
    dataSource: undefined, // 数据来源，评分人
    dimensionaId: undefined, // 纬度id
    goal: undefined, // 考核目标值
    remark: '', // 备注
    isAddStore: false // 是否新增到指标库
  */
  extraData: []
});

let currData = ref(null), // 储存当前的kpi指标
  maxWeight = ref(0), // 储存当前的权重值总和
  currExtraData = ref(), // 储存当前的加减分指标,
  setExtra = ref(true); // 是否设置加减分

// kpi的table字段
const columns: any = reactive([
  {
    title: '序号',
    render: ({ rowIndex }: { rowIndex: number }) => rowIndex + 1,
    width: 80
  },
  {
    title: '指标来源',
    dataIndex: 'source',
    width: 100,
    render: ({ record }: { record: any }) =>
      record.source === 1
        ? '客户类'
        : record.source === 2
        ? '财务类'
        : record.source === 3
        ? '内部运营类'
        : '学习与成长类'
  },
  {
    title: '指标类型',
    dataIndex: 'type',
    width: 100,
    render: ({ record }: { record: any }) =>
      record.type === 1 ? '定性指标' : '定量指标'
  },
  {
    title: '指标名称',
    dataIndex: 'name',
    width: 100
  },
  {
    title: '指标定义',
    dataIndex: 'definition',
    width: 100
  },
  {
    title: '项目界定',
    dataIndex: 'define',
    width: 200
  },
  {
    title: '指标极性',
    dataIndex: 'nature',
    width: 200,
    render: ({ record }: { record: any }) =>
      record.nature === 1 ? '越大越好' : '越小越好'
  },
  {
    title: '指示公式/说明',
    dataIndex: 'formula',
    width: 200
  },
  {
    title: '评分标准/规则',
    dataIndex: 'rule',
    width: 200
  },
  {
    title: '考核目标',
    width: 300,
    headerCellStyle: {
      height: '30px'
    },
    children: [
      {
        title: '考核基准值',
        dataIndex: 'source',
        width: 150,
        headerCellStyle: {
          height: '30px'
        },
        render: ({ record }: any) =>
          record?.target ? record?.target[0].reference : '无'
      },
      {
        title: '考核目标值',
        width: 150,
        headerCellStyle: {
          height: '30px'
        },
        render: ({ record }: { record: any }) =>
          record?.target ? record?.target[0].goal : '无'
      },
      {
        title: '考核挑战值',
        dataIndex: 'source',
        width: 150,
        headerCellStyle: {
          height: '30px'
        },
        render: ({ record }: any) =>
          record?.target ? record?.target[0].challenge : '无'
      }
    ]
  },
  {
    title: '指标权重',
    dataIndex: 'weight',
    width: 100
  },
  // {
  //   title: '数据来源',
  //   dataIndex: 'source',
  //   width: 100
  // },
  {
    title: '实际完成值',
    dataIndex: 'source',
    width: 200
  },
  {
    title: '考核评分',
    dataIndex: 'source',
    width: 100
  },
  {
    title: '指标评分',
    dataIndex: 'goal',
    width: 150
  },
  {
    title: '操作',
    width: 150,
    fixed: 'right',
    slotName: 'optional'
  }
]);

let visible = ref(false); // 新增kpi弹出框

let currIndex = ref(-1); //  储存当前选中kpi的行
// 新增/编辑指标
const add = (record: any, index?: number) => {
  currData.value = null;
  if (index !== undefined) currIndex.value = index;
  else currIndex.value = -1;
  if (record) currData.value = record;
  visible.value = true;
};

// 删除指标
const del = async (record: any, index: number) => {
  if (record.id) {
    await DelProbationTemplateTool({
      id: record.id,
      tool: 1
    });
    KpiData.data.splice(index, 1);
    maxWeight.value = 0;
    KpiData.data.forEach((item: any) => {
      maxWeight.value += item.weight;
    });
  } else {
    KpiData.data.splice(index, 1);
    maxWeight.value = 0;
    KpiData.data.forEach((item: any) => {
      maxWeight.value += item.weight;
    });
  }
};

// kpi弹出框自定义事件
/*
  flag: 判断用户是否点击继续新增，继续为true，否则为false
*/
const kpiIndexEmit = (record: any, flag?: boolean) => {
  // 如果是定性指标
  if (record.type === 1) {
    delete record.target;
    delete record.units;
  }
  if (flag) KpiData.data.push(record);
  else {
    if (currIndex.value !== -1) KpiData.data[currIndex.value] = record;
    else KpiData.data.push(record);
    currIndex.value = -1;
  }
  maxWeight.value = 0;
  KpiData.data.forEach((item: any) => {
    maxWeight.value += item.weight;
  });
};

// 加减分项字段
const extraColumns = reactive([
  {
    title: '序号',
    render: ({ rowIndex }: { rowIndex: number }) => rowIndex + 1,
    width: 80
  },
  {
    title: '指标名称',
    dataIndex: 'name',
    width: 100
  },
  {
    title: '指标定义',
    dataIndex: 'definition',
    width: 200
  },
  {
    title: '项目界定',
    dataIndex: 'define',
    width: 200
  },
  {
    title: '评分标准/规则',
    dataIndex: 'rule',
    width: 200
  },
  {
    title: '考核目标值',
    dataIndex: 'source',
    width: 100
  },
  {
    title: '评分人',
    dataIndex: 'dataSource',
    width: 100
  },
  {
    title: '操作',
    width: 150,
    fixed: 'right',
    slotName: 'optional'
  }
]);
let extraVisible = ref(false); // 新增kpi弹出框
let currExtraIndex = ref(-1); // 储存加减分index
// 新增/编辑指标
const addExtra = (record: any, index?: number) => {
  if (index !== undefined) currExtraIndex.value = index;
  else currExtraIndex.value = -1;
  if (record) currExtraData.value = record;
  extraVisible.value = true;
};

// 删除加减分标
const delExtra = async (record: any, index: number) => {
  if (record.id) {
    await DelProbationTemplateTool({
      id: record.id,
      tool: 7
    });
    KpiData.extraData.splice(index, 1);
  } else {
    KpiData.extraData.splice(index, 1);
  }
};

// kpi加减分弹出框自定义事件
const kpiExtraIndexEmit = (record: any, flag?: boolean) => {
  if (flag) KpiData.extraData.push(record);
  else {
    if (currExtraIndex.value !== -1)
      KpiData.extraData[currExtraIndex.value] = record;
    else KpiData.extraData.push(record);
    currExtraIndex.value = -1;
  }
};

const getData = () => {
  return KpiData;
};

defineExpose({ KpiData, setExtra });
</script>

<style scoped lang="less">
.wrap {
  width: 100%;
  .wrap-header {
    position: relative;
    // width: 100%;
    height: 50px;
    border-radius: 3px;
    background-color: rgb(var(--primary-10));
    line-height: 50px;
    padding: 0 10px;
    margin-bottom: 10px;
  }
  .wrap-header::before {
    display: inline-block;
    content: '';
    width: 5px;
    height: 20px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: #165dff;
  }
  .wrap-header-title {
    margin-left: 10px;
  }
  .wrap-header-title::before {
    content: '*';
    display: inline-block;
    color: red;
  }
  .header {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 50px;
    border-radius: 3px;
    background-color: rgb(var(--primary-10));
    line-height: 50px;
    margin-bottom: 10px;
  }
  :deep(.arco-form-item-label-required-symbol) {
    position: relative;
    top: 35px;
  }
}
</style>
